package com.neo.v1;

import com.neo.util.SystemUtil;

/**
 * 1.4.2
 * 演示线程优先级设置 与 cpu时间片获取机会能力关系
 * 结论:
 * 1,总体而言, 高优先级获得的执行机会更多
 * 2,但是执行机会具有随机性,不一定优先级越高,获取cpu时间片越多
 */
public class V142PriorityDemo {
    private static final int SLEEP_MIC_TIME = 1000;

    static class PrioritySetThread extends Thread{
        static int threadNo = 1;
        public PrioritySetThread(){
            super("thread " + threadNo++);
        }

        public long opportunities = 0;

        @Override
        public void run(){
            while (true){
                opportunities++;
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        PrioritySetThread[] prioritySetThreads = new PrioritySetThread[20];
        for (int i = 0; i < prioritySetThreads.length; i++) {
            prioritySetThreads[i] = new PrioritySetThread();
            SystemUtil.printMsg("i:"+ i+ " no: "+ (i%10 + 1));
            prioritySetThreads[i].setPriority((i%10 + 1));
        }

        for (int i = 0; i < prioritySetThreads.length; i++) {
            prioritySetThreads[i].start();
        }

        Thread.sleep(SLEEP_MIC_TIME);

        for (int i = 0; i < prioritySetThreads.length; i++) {
            prioritySetThreads[i].stop();
        }

        for (int i = 0; i < prioritySetThreads.length; i++) {
            SystemUtil.printMsg(prioritySetThreads[i].getName() + "优先级为: " + prioritySetThreads[i].getPriority()+" 机会值为: " + prioritySetThreads[i].opportunities);

        }
    }
}
